package com.study.algorithm.sort;

import java.util.Arrays;

public class MergeSort {
    public static int[] sort(int[] nums) {
        if (nums.length == 1) {
            return nums;
        }
        int mid = nums.length / 2;
        int[] left = Arrays.copyOfRange(nums, 0, mid);
        int[] right = Arrays.copyOfRange(nums, mid, nums.length);
        return merge(sort(left), sort(right));
    }

    private static int[] merge(int[] left, int[] right) {
        int[] sortedArr = new int[left.length + right.length];
        int idxL = 0, idxR = 0, idxS = 0;
        while (idxL < left.length && idxR < right.length) {
            if (left[idxL] < right[idxR]) {
                sortedArr[idxS++] = left[idxL++];
            } else {
                sortedArr[idxS++] = right[idxR++];
            }
        }
        if (idxL < left.length) {
            while (idxL < left.length) {
                sortedArr[idxS++] = left[idxL++];
            }
        } else {
            while (idxR < right.length) {
                sortedArr[idxS++] = right[idxR++];
            }
        }
        return sortedArr;
    }

    public static void main(String[] args) {
        int[] nums = {1, 5, 8, 7, 1, 2, 5, 4, 66, 5, 84, 5, 110, 4, 5, 4};
        int[] sorted = sort(nums);
        System.out.println("nums = " + Arrays.toString(sorted));
    }
}
